//
//  BTChatViewController.m
//  WeChat
//
//  Created by 互联网 on 16/11/4.
//  Copyright © 2016年 bigtree. All rights reserved.
//

#import "BTChatViewController.h"

@interface BTChatViewController ()<NSFetchedResultsControllerDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    NSFetchedResultsController *_fetchedResultsController;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/**
 *  输入框需要底部的约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@end

@implementation BTChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置键盘的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    //加载数据库的数据
    // 1. 获取上下文
  NSManagedObjectContext *msgArchivingContext = [BTXMPPTool sharedBTXMPPTool].msgArchivingStorage.mainThreadManagedObjectContext;
    // 2. 查询请求
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    // 3. 过滤（当前登录用户 并且是好友的聊天消息）
    NSString *loginUserJid = [BTXMPPTool sharedBTXMPPTool].xmppStream.myJID.bare;
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",loginUserJid,self.friendJid.bare];
    fetchRequest.predicate = pre;
    
    //4. 设置时间排序
    NSSortDescriptor *msgSort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    fetchRequest.sortDescriptors = @[msgSort];
    
    //5. 执行函数
    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:msgArchivingContext sectionNameKeyPath:nil cacheName:nil];

    // 设置代理
    _fetchedResultsController.delegate = self;
    
    NSError *err = nil;
    [_fetchedResultsController performFetch:&err];
    
    BTLog(@"%@",_fetchedResultsController.fetchedObjects);

}
#pragma mark --数据库内容改变时调用
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    BTLog(@"数据库值改变");
    [self.tableView reloadData];
    
    // 表格滚动到底部
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_fetchedResultsController.fetchedObjects.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
#pragma mark -- 表格数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _fetchedResultsController.fetchedObjects.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *chatID  = @"chatCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:chatID];
   XMPPMessageArchiving_Message_CoreDataObject *msg = _fetchedResultsController.fetchedObjects[indexPath.row];
    
    // 判断消息的类型有没有附加
    // 1. 获取原始的xml数据
    XMPPMessage *message = msg.message;
    // 获取附件类型
    NSString *bodyType = [message attributeStringValueForName:@"bodyType"];
    if ([bodyType isEqualToString:@"image"]) { // 图片
        // 2. 遍历message的子节点
        NSArray *child = message.children;
        for (XMPPElement *note in child) {
            // 获取子节点的名字
            if ([[note name] isEqualToString:@"attachment"]) {
                BTLog(@"获取到附件。。。");
                // 获取到附加的字符串，然后转成NSData,最后转成UIImage
                NSString *imgStr = [note stringValue];
                NSData *imgData = [[NSData alloc]initWithBase64EncodedString:imgStr options:0];
                UIImage *img = [UIImage imageWithData:imgData];
                cell.imageView.image = img;
            }
        }
 
    }else{
        cell.textLabel.text = msg.body;
    }
        return cell;
}

#pragma mark -- 键盘显示时调用
-(void)kbWillShow:(NSNotification *)noti
{  // 获取键盘的高度
    CGFloat kbHeight = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    self.bottomConstraint.constant = kbHeight;
}

#pragma mark --键盘隐藏时调用
-(void)kbWillHide:(NSNotification *)noti
{
    self.bottomConstraint.constant = 0;
}

#pragma mark 发送聊天数据
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *txt = textField.text;
    
    // 怎么发送聊天数据
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
    [msg addBody:txt];
    [[BTXMPPTool sharedBTXMPPTool].xmppStream sendElement:msg];
    // 清空发送框
    textField.text = nil;
    return YES;
}

#pragma mark -- 表格滚动，隐藏键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark 图片选择按钮点击
- (IBAction)imgChooseBtnClick:(id)sender {
    // 从图片库选择图片
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    BTLog(@"%@",info);
    // 获取原始图片
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    [self sendAttachmentWithData:UIImagePNGRepresentation(img) bodyType:@"image"];
    // 图片选择控制器隐藏
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 发送图片附件
-(void)sendAttachmentWithData:(NSData *)data bodyType:(NSString *)bodyType{
    //发送图片
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
    
    //设置类型
    [msg addAttributeWithName:@"bodyType" stringValue:bodyType];
#pragma mark 没有body就不认
    [msg addBody:bodyType];
    //把附件经过"base64编码"转成字符串
    NSString *base64Str = [data base64EncodedStringWithOptions:0];
    
    //定义附件
    XMPPElement *attachment = [XMPPElement elementWithName:@"attachment" stringValue:base64Str];
    
    //添加字节点
    [msg addChild:attachment];
    [[BTXMPPTool sharedBTXMPPTool].xmppStream sendElement:msg];
}
/*-(void)sendAttachmentWithImg:(UIImage *)img{
    // 发送图片
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
    [msg addBody:@"image"];
    // 把图片经过“base64编码”转化成字符串
    // 1.把图片转成NSData
    NSData *imgData = UIImagePNGRepresentation(img);
    
    // 2.把NSData转成base64字符串
    NSString *imgStr = [imgData base64EncodedStringWithOptions:0];
    
    // 3.定义附件
    XMPPElement *attachment = [XMPPElement elementWithName:@"attachment" stringValue:imgStr];
    
    // 4.添加子节点
    [msg addChild:attachment];
    
    // 5.发送消息到服务器
    [[BTXMPPTool sharedBTXMPPTool].xmppStream sendElement:msg];
    
}*/

@end
